package com.leap.utils;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.leap.entity.Message;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;

public class KimiChatClient {

    private static final String API_URL = "https://api.moonshot.cn/v1/chat/completions";

    private String apiKey;

    public KimiChatClient(String apiKey) {
        this.apiKey = apiKey;
    }

    public Message sendRequest(List<Message> messageList) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpPost httpPost = new HttpPost(API_URL);
            JSONArray messages = (JSONArray) JSON.toJSON(messageList);

            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + apiKey);

            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "moonshot-v1-8k");
            requestBody.put("temperature", 0.3);
            requestBody.put("messages", messages);

            System.out.println(requestBody);

            StringEntity entity = new StringEntity(requestBody.toString(), "UTF-8");
            entity.setContentType("application/json");
            entity.setContentEncoding("utf-8");

            httpPost.setEntity(entity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new RuntimeException("API请求失败！" + response.getStatusLine());
                }
                JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()));
                JSONObject object = jsonObject.getJSONArray("choices")
                        .getJSONObject(0)
                        .getJSONObject("message");
                return JSON.parseObject(object.toJSONString(), Message.class);

            }

        }
    }
}
